package com.jason.www.controller;

import com.alibaba.fastjson.JSONObject;
import com.jason.www.commons.exception.BusiException;
import com.jason.www.controller.vo.GiftCardVo;
import com.jason.www.service.IGiftCardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * <p>
 * 购物卡  前端控制器
 * </p>
 *
 * @author JasonChoi
 * @since 2018-09-13
 */
@RestController
@RequestMapping("/giftcard")
public class GiftCardController {
    @Autowired
    IGiftCardService giftCardService;
    /**
     * 后台获取购物卡列表 条件查询 + 分页
     * @return
     */
//    @ResponseBody
//    @RequestMapping(value = "/list" , method = RequestMethod.POST)
//    public Page<GiftCard> searchGiftCardList(@RequestBody GiftCardVo vo){
//        return giftCardService.findGiftCardList(vo);
//    }
    
    /**
     * 后台购物卡列表导出 条件查询 + 导出
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/search/download", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public void downloadSearchGiftCardList(HttpServletResponse response,@RequestBody GiftCardVo vo) throws Exception {
        giftCardService.downloadGiftCardExcel(response,vo);
    }


    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public String upload(@RequestParam(value = "file", required = false) MultipartFile file) {
        JSONObject jsonObj = new JSONObject();
        try {
            String fileName = file.getOriginalFilename();
            InputStream ips = file.getInputStream();
            String msg = giftCardService.batchInsertByFile(ips, fileName);
            jsonObj.put("success", true);
            jsonObj.put("msg", msg);
        } catch (IOException e) {
            jsonObj.put("success", false);
        } catch (BusiException e) {
            jsonObj.put("success", false);
            jsonObj.put("errInf", e.getMessage());
        }
        return jsonObj.toJSONString();
    }
}
